package com.cchc.k8s.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * file：GlobalExceptionHandler.java
 * description:全局异常捕获
 * date: 2021-09-18 09:15
 * author: wenrui
 * version: 1.0
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.cchc.k8s"})
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object> {

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({K8sException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResult APIExceptionHandler(K8sException e) {
        log.error(e.toString());
        return BaseResult.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<Object> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("方法参数校验异常:{}", e.getMessage());
        List<String> list = new ArrayList<>();
        if (!e.getBindingResult().getAllErrors().isEmpty()) {
            Iterator var3 = e.getBindingResult().getAllErrors().iterator();

            while (var3.hasNext()) {
                ObjectError error = (ObjectError) var3.next();
                list.add(error.getDefaultMessage());
            }
        }

        return BaseResult.fail(ResultCode.VALIDATE_FAILED.getCode(), list.toString());
    }

    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return !methodParameter.getGenericParameterType().equals(BaseResult.class);
    }

    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return BaseResult.success(data);
    }
}
